package com.jstyle.beatecg.activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.jstyle.beatecg.NetWork.NetWorkUtil;
import com.jstyle.beatecg.NetWork.api.JstyleApi;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.base.BaseActivity;
import com.jstyle.beatecg.model.NetResultData;
import com.jstyle.beatecg.util.NetWorkConast;
import com.jstyle.beatecg.util.SHA1;
import com.jstyle.beatecg.util.ScreenUtils;
import com.jstyle.beatecg.view.EditTextWithDelete;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
/**
 * 找回密码
 */
public class FindPasswordActivity extends BaseActivity {
    private static final String TAG = "FindPasswordActivity";
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.bt_findpassword_back)
    ImageView btFindpasswordBack;
    @BindView(R.id.bt_findpassword_countrycode)
    Button btFindpasswordCountrycode;
    @BindView(R.id.et_findpassword_phonenumber)
    EditTextWithDelete etFindpasswordPhonenumber;
    @BindView(R.id.et_findpassword_Verification_Code)
    EditTextWithDelete etFindpasswordVerificationCode;
    @BindView(R.id.bt_findpassword_get_Verification_Code)
    Button btFindpasswordGetVerificationCode;
    @BindView(R.id.et_findpassword_password)
    EditTextWithDelete etFindpasswordPassword;
    @BindView(R.id.et_findpassword_confimpassword)
    EditTextWithDelete etFindpasswordConfimpassword;
    @BindView(R.id.bt_findpassword_findpassword)
    Button btFindpasswordFindpassword;
    private Disposable subscription;
    Observer<NetResultData> observer = new Observer<NetResultData>() {

        @Override
        public void onError(Throwable e) {
            disMissProgressDialog();
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(NetResultData netResultData) {
            disMissProgressDialog();
            int msgCode = netResultData.getMsgCode();
            String msg = NetWorkConast.getResult(msgCode,FindPasswordActivity.this);
            if(msgCode==NetResultData.Success_Code){
                msg=getString(R.string.find_pwd_successful);
                finish();

            }else if(msgCode==NetResultData.Failed_Code){
                msg=getString(R.string.find_pwd_failed);
            }
            showToast(msg);
        }
    };
    private String countryCode="0086-";
    private String language;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_password);
        ButterKnife.bind(this);
        showStatusBar();
        Locale locale = getResources().getConfiguration().locale;
        language = locale.getLanguage();
    }

    @Override
    protected void showStatusBar() {
        ScreenUtils.setStatusBarColor(llTitle,getResources().getColor(R.color.colorPrimary));
     //   ScreenUtils.setStatusBarColor(llTitle, Color.WHITE);

    }

    @OnClick({R.id.bt_findpassword_back,R.id.bt_findpassword_findpassword ,R.id.bt_findpassword_countrycode, R.id.bt_findpassword_get_Verification_Code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_findpassword_back:
                finish();
                break;
            case R.id.bt_findpassword_countrycode:
                break;
            case R.id.bt_findpassword_get_Verification_Code:
                getVerificationCode();
                break;
            case R.id.bt_findpassword_findpassword:
                findPassword();
                break;
        }
    }

    private void findPassword() {
        if(!NetWorkUtil.isNetworkConnected(this)){
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etFindpasswordPhonenumber.getText().toString();
        String password = etFindpasswordPassword.getText().toString();
        String confimPassword = etFindpasswordConfimpassword.getText().toString();
        String verCode = etFindpasswordVerificationCode.getText().toString();
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(account) || TextUtils.isEmpty(confimPassword) || TextUtils.isEmpty(verCode)) {
            showToast(getString(R.string.fill_all_info));
            return;
        }
        if (!password.equals(confimPassword)) {
            showToast(getString(R.string.sure_psd_same));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if(language.equals("zh")){
            map.put(NetWorkConast.KEY_PHONE,countryCode+account);
        }else{
            map.put(NetWorkConast.KEY_userEmail,account);
        }
        map.put(NetWorkConast.KEY_userpwd, SHA1.md5Encoder(password));
        map.put(NetWorkConast.KEY_smsCode,verCode);
        NetWorkUtil.addSHA1(map);
        NetWorkUtil.getInstance().getJstyleApi().findPassword(map).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showProgressDialog(getString(R.string.Find_Passwording));
            }

        }).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
    }

    private void getVerificationCode() {
        if(!NetWorkUtil.isNetworkConnected(this)){
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etFindpasswordPhonenumber.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast(getString(R.string.login_input_phone));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if(language.equals("zh")){
            map.put(NetWorkConast.KEY_PHONE,countryCode+account);
            map.put(NetWorkConast.KEY_reqType,NetWorkConast.ZH_CN);
        }else{
            map.put(NetWorkConast.KEY_userEmail,account);
            map.put(NetWorkConast.KEY_reqType,NetWorkConast.ZH_EN);
        }

        NetWorkUtil.addSHA1(map);
        JstyleApi jstyleApi=NetWorkUtil.getInstance().getJstyleApi();
        Observable<NetResultData>observable= language.equals("zh")?jstyleApi.getSmsCode(map):jstyleApi.getEmailCode(map);
        observable.subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showProgressDialog(getString(R.string.Get_verification_codeing));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<NetResultData>() {

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData netResultData) {
                disMissProgressDialog();
                int msgCode = netResultData.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode,FindPasswordActivity.this);
                Log.i(TAG, "onNext: "+netResultData.toString());
                if (msgCode == NetResultData.Success_Code) {
                    startTimer();
                    msg=getString(R.string.Get_verification_code_sucessfule);
                }
                showToast(msg);

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
    }

    private void getCountryCode() {
    /*    phone.showForResult(this, (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                String currentId = (String) data.get("id");
                String[] res = SMSSDK.getCountry(currentId);
                btFindpasswordCountrycode.setText("+" + res[1]);
                countryCode="00"+res[1]+"-";
            }
        });*/
    }
    private void startTimer() {
        btFindpasswordGetVerificationCode.setEnabled(false);
         Observable.intervalRange(0,60,0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {



            @Override
            public void onError(Throwable e) {

            }

             @Override
             public void onComplete() {

             }

             @Override
             public void onSubscribe(Disposable d) {

             }

             @Override
            public void onNext(Long aLong) {

                btFindpasswordGetVerificationCode.setText(String.format(getResources().getString(R.string.formatsecond), 60 - aLong));
                if (aLong == 59) {
                    btFindpasswordGetVerificationCode.setEnabled(true);
                    btFindpasswordGetVerificationCode.setText(getString(R.string.sign_get_vcode));
                    unsubscribe();
                }

            }
        });
    }
    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }
}
